(function (window, undefined) {
  var that;
  const map = document.getElementById("map");
  function Game() {
    this.food = new Food();
    this.snake = new Snake();
    //存入游戏地图
    this.map = map;
    that = this;
  }
  Game.prototype.start = function () {
    this.food.render(this.map);
    this.food.render(this.map);
    this.food.render(this.map);
    this.snake.render(this.map);
    runSnake(this.map);
    bindKeyCode();
  };
  function runSnake(map) {
    let timer = setInterval(() => {
      that.snake.move(map);
      that.snake.remove(map);
      that.snake.render(map);

      //获取当前蛇头坐标位置
      let HX = that.snake.body[0].x;
      let HY = that.snake.body[0].y;
      // 获取蛇头的具体坐标位置，px值
      let headX = HX * that.snake.width;
      let headY = HY * that.snake.height;
      for (let i = 1; i < that.snake.body.length; i++) {
        if (HX === that.snake.body[i].x && HY === that.snake.body[i].y) {
          clearInterval(timer);
          alert("咬到自己了，游戏结束");
        }
      }
      ////每次移动一次都要判断是否吃到食物
      /* 
    1，每次蛇头移动时都要判断是否吃到食物，即食物与蛇头位置重叠；
    2，食物被吃掉，移除被吃掉的食物；
    3，生成新的食物，并且蛇增加一节
    */
      for (let i = 0; i < that.food.elements.length; i++) {
        //蛇头与食物坐标重合，食物被吃掉，同时蛇增加一节蛇
        if (that.food.elements[i].offsetLeft === headX && that.food.elements[i].offsetTop === headY) {
          // 生成新的食物
          that.food.remove(that.map, i);
          that.food.render(that.map);
          // 吃到食物蛇增加一节
          let last = that.snake.body[that.snake.body.length - 1];
          that.snake.body.push({
            x: last.x,
            y: last.y,
            backgroundColor: last.backgroundColor,
          });
          break;
        }
      }
      //每次移动一次都要判断是否走出地图
      if (HX < 0 || HX >= map.clientWidth / that.snake.width || HY < 0 || HY >= map.clientHeight / that.snake.height) {
        clearInterval(timer);
        alert("game over!");
      }
    }, 150);
  }
  function bindKeyCode() {
    document.onkeydown = function (e) {
      // console.dir(e.keyCode);
      switch (e.keyCode) {
        //左
        case 37:
          that.snake.direction = "left";
          break;
        //上
        case 38:
          that.snake.direction = "top";
          break;
        //右
        case 39:
          that.snake.direction = "right";
          break;
        //下
        case 40:
          that.snake.direction = "bottom";
          break;
        default:
          break;
      }
      // that.snake.move(map);
      // that.snake.remove(map);
      // that.snake.render(map);
    };
  }
  window.Game = Game;
})(window, undefined);
